﻿import cv2


def hfs(num_ave_inw):
    """
    红富士类型的苹果糖度计算
    """
    return 31.775 - 0.29352 * (round(num_ave_inw[29], 1)) + 0.27997 * (round(num_ave_inw[59], 1)) - 0.30134 * (
        round(num_ave_inw[89], 1)) + 0.16827 * (round(num_ave_inw[119], 1)) - 0.11951 * (
               round(num_ave_inw[149], 1)) + 0.1967 * (round(num_ave_inw[179], 1)) - 0.22352 * (
               round(num_ave_inw[209], 1)) + 0.31529 * (round(num_ave_inw[239], 1)) - 0.38966 * (
               round(num_ave_inw[269], 1)) + 0.37202 * (round(num_ave_inw[299], 1)) - 0.53451 * (
               round(num_ave_inw[329], 1))


def hys(num_ave_inw):
    """
    黄元帅类型的苹果糖度计算
    """
    return -40.277 + 2.8541 * (round(num_ave_inw[149], 1)) - 4.1461 * (round(num_ave_inw[169], 1)) + 0.84569 * (
        round(num_ave_inw[189], 1)) + 0.89977 * (round(num_ave_inw[209], 1)) - 0.77124 * (
               round(num_ave_inw[249], 1)) + 2.693 * (round(num_ave_inw[269], 1)) - 1.016 * (
               round(num_ave_inw[289], 1)) - 1.0349 * (round(num_ave_inw[309], 1)) + 0.66656 * (
               round(num_ave_inw[329], 1))


def tx(num_ave_inw):
    """
    糖心类型的苹果糖度计算
    """
    return -3.7449 - 0.19894 * (round(num_ave_inw[29], 1)) - 0.22811 * (round(num_ave_inw[59], 1)) + 0.53478 * (
        round(num_ave_inw[89], 1)) + 0.089082 * (round(num_ave_inw[119], 1)) - 0.058781 * (
               round(num_ave_inw[149], 1)) - 0.11904 * (round(num_ave_inw[179], 1)) - 0.072481 * (
               round(num_ave_inw[209], 1)) + 0.39082 * (round(num_ave_inw[239], 1)) - 0.91858 * (
               round(num_ave_inw[269], 1)) + 0.54754 * (round(num_ave_inw[299], 1)) + 0.19833 * (
               round(num_ave_inw[329], 1))


# 计算苹果糖度的函数字典, key对应着用户的choice, 详见compute函数的choice参数
# 函数使用的计算方式为: 多项式拟合模型，采用不同横轴点的灰度平均来计算
sugarComputeFuncs = {
    0: hfs,
    1: hys,
    2: tx,
}


def compute(choice, filepath):
    """
    :param choice 用户做出的选择, 对应如下
        0-红富士
        1-黄元帅
        2-溏心

    :param filepath 文件路径
    """
    image_gray = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)  # 按照灰度模式读取图片
    gray_dst = image_gray[1910:2320, 2290:2630]  # 裁剪图片

    rows, cols = gray_dst.shape
    w = cols
    h = rows
    count = 0
    num = [[0 for _ in range(0, h)] for _ in range(0, w)]
    num_ave_inw = [0 for _ in range(0, w)]

    for i in range(0, w):
        for j in range(0, h):
            num[i][j] = int(gray_dst[j, i])  # gray指灰度图像， xy指哪一点，意思是输出灰度图像一点的数值，也就是灰度值
            count += int(gray_dst[j, i])  # gray_j_i，即高度为j宽度为i的点（不要搞反了）
        ave = count / rows  # 求横轴一点上所有竖轴的灰度值的平均
        num_ave_inw[i] = ave
        count = 0

    # 根据choice计算糖度并返回
    return sugarComputeFuncs[choice](num_ave_inw)
